define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', 'jstree'], function ($, undefined, Backend, Table, Form, Template) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yungift/gift/main/index' + location.search,
                    add_url: 'yungift/gift/main/add',
                    edit_url: 'yungift/gift/main/edit',
                    // del_url: 'yungift/gift/main/del',
                    multi_url: 'yungift/gift/main/multi',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        // 该列为复选框字段,如果后台的返回state值将会默认选中
                        {
                            field: 'state',
                            checkbox: true
                        },
                        // sortable为是否排序,operate为搜索时的操作符,visible表示是否可见
                        {
                            field: 'id',
                            title: 'ID',
                            sortable: true,
                            operate: false
                        },
                        // 模糊搜索
                        {
                            field: 'name',
                            title: __('Name'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                        },
                        {
                            field: 'type',
                            title: __('类型'),
                            searchList: Config.typeList,
                            formatter: Table.api.formatter.label
                        },
                        {
                            field: 'multi_spec',
                            title: __('多规格'),
                            searchList: {0: '否', 1: '是'},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'worth',
                            title: __('价格'),
                            sortable: true,
                            // operate: false
                            operate: 'BETWEEN',
                        },
                        /*
                        {
                            field: 'amount',
                            title: __('礼币'),
                            sortable: true,
                            operate: false
                        },
                        */
                        {
                            field: 'count_left',
                            title: __('库存'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'count_gain',
                            title: __('已领取'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'note',
                            title: __('备注'),
                        },
                        {
                            field: 'choose',
                            title: __('选择'),
                            searchList: Config.chooseList,
                            formatter: function (value, row, index) {
                                var modelIds = [];
                                if (Config.modelType === 'activity') {
                                    modelIds = row.activity_ids ? row.activity_ids.split(',') : [];
                                } else if (Config.modelType === 'card') {
                                    modelIds = row.card_ids ? row.card_ids.split(',') : [];
                                }

                                if (modelIds.indexOf(Config.modelId) !== -1) {
                                    return '<a class="btn-change text-success" data-url="yungift/gift/main/bind" data-id="' + row.id + '" data-action="no" data-params="model_type=' + Config.modelType + '&model_id=' + Config.modelId + '"><i class="fa fa-toggle-on fa-2x"></i></a>';
                                }
                                return '<a class="btn-change" data-url="yungift/gift/main/bind" data-id="' + row.id + '" data-action="yes" data-params="model_type=' + Config.modelType + '&model_id=' + Config.modelId + '"><i class="fa fa-toggle-on fa-flip-horizontal text-gray fa-2x"></i></a>';
                            },
                            visible: Config.modelId,
                            searchable: Config.modelId,
                        },
                        {
                            field: 'start_time',
                            title: __('上架时间'),
                            sortable: true,
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        {
                            field: 'end_time',
                            title: __('下架时间'),
                            sortable: true,
                            formatter: function (value, row, index) {
                                if (value === 0) {
                                    return '长期有效';
                                }
                                return Table.api.formatter.datetime(value, row, index);
                            },
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        // {
                        //     field: 'activityId',
                        //     title: __('限定活动'),
                        //     searchList: Config.activityList,
                        //     formatter: function (value, row, index) {
                        //         return row.activity_ids ? '是' : '否';
                        //     },
                        //     visible: !Config.modelId,
                        //     searchable: !Config.modelId,
                        // },
                        {
                            field: 'groupId',
                            title: __('限定礼卡'),
                            searchList: Config.cardList,
                            formatter: function (value, row, index) {
                                return row.card_ids ? '是' : '否';
                            },
                            visible: !Config.modelId,
                            searchable: !Config.modelId,
                        },
                        // {
                        //     field: 'groupId',
                        //     title: __('限定分组'),
                        //     searchList: Config.groupMap,
                        //     formatter: function (value, row, index) {
                        //         return row.group_ids ? '是' : '否';
                        //     }
                        // },
                        {
                            field: 'weight',
                            title: __('权重'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: Config.statusList,
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'updated_at',
                            title: __('Update time'),
                            sortable: true,
                            operate: false,
                            formatter: Table.api.formatter.datetime,
                        },
                        {
                            field: 'created_at',
                            title: __('Create time'),
                            sortable: true,
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        // 操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                        {
                            field: 'operate',
                            width: '150px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'code',
                                    text: __('券码'),
                                    title: function (row) {
                                        return __('券码管理') + ' - ' + row.name;
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    icon: 'fa fa-tags',
                                    url: function (row) {
                                        return 'yungift/gift/code/index?gift_id=' + row.id;
                                    },
                                    visible: function (row) {
                                        return row.type === 2;
                                    },
                                },
                                {
                                    name: 'order',
                                    text: __('订单'),
                                    title: function (row) {
                                        return __('相关订单') + ' - ' + row.name;
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    visible: function (row) {
                                        return row.count_gain > 0;
                                    },
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    icon: 'fa fa-list',
                                    url: function (row) {
                                        return 'yungift/gift/order/index?gift_id=' + row.id;
                                    },
                                },
                            ],
                            formatter: Table.api.formatter.operate
                        },
                    ],
                ],
                // 快捷搜索,这里可在控制器定义快捷搜索的字段
                search: false,
                // 启用普通表单搜索
                commonSearch: true,
                // 显示切换视图（table/card）按钮
                showToggle: false,
                // 显示导出按钮
                showExport: false,
                // 启用跨页选择
                maintainSelected: true,
                // 启用固定列
                fixedColumns: true,
                // 固定右侧列数
                fixedRightNumber: 1,
                // 可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: true,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            table.on('load-success.bs.table', function (data) {
                // 编辑窗口大小
                $(".btn-editone").data('area', ['100%', '100%']);
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                // 类型
                $(document).on("change", "#c-type", function () {
                    var value = $(this).val();
                    var multiSpec = $("#c-multi_spec").val();
                    console.log("type change", value, multiSpec);
                    if (value === "1" && multiSpec === "0") {
                        $("#box-count_left").removeClass("hide");
                    } else {
                        $("#box-count_left").addClass("hide");
                    }
                    if (value === "1") {
                        $("#box-specs").removeClass("no-count-left");
                        $("#box-external_link").addClass("hide");
                        $("#box-gain_methods").removeClass("hide");
                        $("#box-offline_place").removeClass("hide");
                    } else {
                        $("#box-specs").addClass("no-count-left");
                        $("#box-external_link").removeClass("hide");
                        $("#box-gain_methods").addClass("hide");
                        $("#box-offline_place").addClass("hide");
                    }
                });

                // 多规格
                $(document).on("change", "#c-multi_spec", function () {
                    var value = $(this).val();
                    console.log("multi_spec change", value);
                    if (value === "1") {
                        $("#box-specs").removeClass("hide");
                        $("#box-amount-worth").addClass("hide");
                        $("#box-count_left").addClass("hide");
                    } else {
                        $("#box-specs").addClass("hide");
                        $("#box-amount-worth").removeClass("hide");
                        $("#box-count_left").removeClass("hide");
                    }
                });

                // 领取方式 - 线下领取
                $(document).on("change", "#c-gain_methods-1", function () {
                    var value = $(this).prop('checked');
                    console.log("gain_methods-1 change", value);
                    if (value) {
                        $("#box-offline_place").removeClass("hide");
                    } else {
                        $("#box-offline_place").addClass("hide");
                    }
                });

                // 领取方式 - 快递邮寄
                $(document).on("change", "#c-gain_methods-2", function () {
                    var value = $(this).prop('checked');
                    console.log("gain_methods-2 change", value);
                });

                // 读取选中的条目 - 新增方法
                $.jstree.core.prototype.get_all_checked = function (full) {
                    var obj = this.get_selected(), i, j;
                    for (i = 0, j = obj.length; i < j; i++) {
                        obj = obj.concat(this.get_node(obj[i]).parents);
                    }
                    obj = $.grep(obj, function (v, i, a) {
                        return v !== '#';
                    });
                    obj = obj.filter(function (itm, i, a) {
                        return i === a.indexOf(itm);
                    });
                    return full ? $.map(obj, $.proxy(function (i) {
                        return this.get_node(i);
                    }, this)) : obj;
                };

                // 渲染权限节点树
                Controller.api.renderTree(Config.groupTreeList);

                // 全选和展开
                $(document).on("click", "#checkAll", function () {
                    $("#treeView").jstree($(this).prop("checked") ? "check_all" : "uncheck_all");
                });
                $(document).on("click", "#expandAll", function () {
                    $("#treeView").jstree($(this).prop("checked") ? "open_all" : "close_all");
                });
                $(document).on("fa.event.appendfieldlist", '[data-name="row[data]"] .btn-append', function (e, obj) {
                    $(".fieldlist input:first-child").trigger("change");
                });

                Form.api.bindevent($("form[role=form]"), null, null, function () {
                    var type = $("#c-type").val();
                    var multiSpec = $("#c-multi_spec").val();
                    var specs = $("#c-specs").val();
                    console.log('before submit', type, multiSpec, specs);
                    if (multiSpec === '1') {
                        specs = JSON.parse(specs);
                        if (specs.length === 0) {
                            Toastr.error("规格不能为空");
                            return false;
                        }
                    }

                    // 领取方式
                    if (type === '1') {
                        var hasGainMethods = false;
                        $("form[role=form]").serializeArray().forEach(function (item) {
                            if (item.name.indexOf('gain_methods') !== -1) {
                                hasGainMethods = true;
                            }
                        });
                        if (!hasGainMethods) {
                            Toastr.error("必须选择领取方式");
                            return false;
                        }
                    }

                    // 权限节点
                    if ($("#treeView").size() > 0) {
                        var value = $("#treeView").jstree("get_all_checked");
                        $("input[name='row[group_ids]']").val(value.join(','));
                    }

                    return true;
                });
            },
            renderTree: function (content) {
                $("#treeView").on('redraw.jstree', function (e) {
                    $(".layer-footer").attr("domrefresh", Math.random());
                }).jstree({
                    "themes": {"stripes": true},
                    "checkbox": {
                        "keep_selected_style": false,
                    },
                    "types": {
                        "root": {
                            "icon": "fa fa-folder-open",
                        },
                        "menu": {
                            "icon": "fa fa-folder-open",
                        },
                        "file": {
                            "icon": "fa fa-file-o",
                        }
                    },
                    "plugins": ["checkbox", "types"],
                    "core": {
                        'check_callback': true,
                        "data": content
                    }
                });
            },
            formatter: {  // 渲染的方法
            },
            events: { // 绑定事件的方法
            }
        }
    };
    return Controller;
});
